package com.hyphenate.easeui.dao;

import android.content.Context;

import com.hyphenate.easeui.EaseConstant;
import com.rockerhieu.emojicon.emoji.SerializeManager;

import java.util.List;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.query.DeleteQuery;
import de.greenrobot.dao.query.QueryBuilder;
import de.greenrobot.dao.query.WhereCondition;

@SuppressWarnings({"rawtypes", "unchecked"})
public class DaoHelper<T> {

    private static DaoHelper instance;
    private DaoSession mDaoSession;
    private AbstractDao<T, Long> tDao;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;
    private static String name;
    private DaoHelper() {
    }

    public static DaoHelper getInstance(Context context, String TABLENAME) {
        name=TABLENAME;
        if (instance == null) {
            instance = new DaoHelper();
        }
        String uid= (String) SerializeManager.loadFile(EaseConstant.currentId)+"";
        instance.mDaoSession = getDaoSession(context,uid);
        if(TABLENAME.equals(EaseConstant.DB_NAME_CHAT))
            instance.tDao = instance.mDaoSession.getUserBeanDao();
        else if(TABLENAME.equals(EaseConstant.DB_NAME_GROUP)){
            instance.tDao=instance.mDaoSession.getGroupChatBeanDao();
        }else if(TABLENAME.equals(EaseConstant.DB_NAME_TOPIC_IMAGE)){
            instance.tDao = instance.mDaoSession.getTopicImageDao();
        }else if(TABLENAME.equals(EaseConstant.DB_NAME_REPLY_IMAGE)){
            instance.tDao = instance.mDaoSession.getReplyImageDao();
        }
        return instance;
    }
    /**
     * 取得DaoMaster
     *
     * @param context
     * @return
     */
    public static DaoMaster getDaoMaster(Context context, String TABLENAME) {
        if (daoMaster == null) {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, TABLENAME,
                    null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    /**
     * 取得DaoSession
     *
     * @param context
     * @return
     */
    public static DaoSession getDaoSession(Context context, String TABLENAME) {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context, TABLENAME + "_edgdb");
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }
    public List<T> loadAllT() {
        instance.mDaoSession.clear(name);
        return instance.tDao.loadAll();
    }

    public List<T> queryTLists(WhereCondition where) {
        QueryBuilder<T> builder = instance.tDao.queryBuilder();
        return builder.where(where).list();
    }

    public List<T> queryTLists(QueryBuilder<T> builder,WhereCondition where){
        return builder.where(where).list();
    }

    public QueryBuilder<T> getQueryBuilder(){
        return instance.tDao.queryBuilder();
    }

    public T updateT(T t) {
        instance.mDaoSession.clear(name);
        instance.tDao.update(t);
        return t;
    }

    /**
     * insert or update noteList use transaction
     */
    public void saveTLists(final List<T> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        tDao.getSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < list.size(); i++) {
                    T t = list.get(i);
                    tDao.insertOrReplace(t);
                }
            }
        });

    }

    public void deleteById(String mId) {
        QueryBuilder<T> builder = instance.tDao.queryBuilder();
        DeleteQuery<T> bd = builder.where(tDao.getProperties()[1].eq(mId)).buildDelete();
        bd.executeDeleteWithoutDetachingEntities();
    }
    //查询某个表是否包含某个id
    public boolean isHas(Property p, String imid){
        instance.mDaoSession.clear(name);
        QueryBuilder  qb = instance.tDao.queryBuilder();
        qb.where(p.eq(imid));
        qb.buildCount().count();
        return qb.buildCount().count() > 0 ? true : false;
    }

    public void insert(T t){
        instance.mDaoSession.clear(name);
        instance.tDao.insert(t);
    }
    /** 通过id查找其目录id */
    public T getTypeId(Property p, String picId){
        instance.mDaoSession.clear(name);
        T s = null;
        try {
            s = (T) instance.tDao.queryBuilder().where(
                   p.eq(picId)).unique();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    public void update(T t){
        instance.mDaoSession.clear(name);
        instance.tDao.update(t);
    }

    public void delete(T t) {
        instance.tDao.delete(t);
    }

    public void deleteAll(){
        instance.tDao.deleteAll();
    }

    //查询某个表是否包含某个id 多条件查询
    public boolean isHas(Property p1, String str1,Property p2,String str2){
        instance.mDaoSession.clear(name);
        QueryBuilder  qb = instance.tDao.queryBuilder();
        qb.where(qb.and(p1.eq(str1),p2.eq(str2)));
        qb.buildCount().count();
        return qb.buildCount().count() > 0 ? true : false;
    }

    public void deleteById(Property p,String id){
        QueryBuilder<T> builder = instance.tDao.queryBuilder();
        DeleteQuery<T> bd = builder.where(p.eq(id)).buildDelete();
        bd.executeDeleteWithoutDetachingEntities();
    }
}